jweb.util.Visualizer = function() {
  this.appendEl = $('div#console');
  this.subscriberId=null;
  this.audioContext = null;
  this.start();
}
jweb.util.Visualizer.prototype = {
	onMessage:function(subj, msg, data) {
		if(subj == constants.contextInited){
			this.audioContext = msg.audioContext;//refer the obj
		}
		else if('AnalyserReady' == subj){
			this.analyser = msg.analyser;
		}
		
		if(this.analyser!=null&&this.audioContext!=null){
			this._visualize();
		}
	},
	_visualize:function(){
        var analyser = this.analyser;
        //var array = new Uint8Array(analyser.frequencyBinCount);
        //analyser.getByteFrequencyData(array);
        
        var canvas = document.getElementById('clip2'),
        cwidth = canvas.width,
        cheight = canvas.height - 10,
        meterWidth = 10, //width of the meters in the spectrum
        gap = 0, //gap between meters
        capHeight = 2,
        capStyle = '#fff',
        meterNum = 300 / 12, //count of the meters
        //capYPositionArray = []; ////store the vertical position of hte caps for the preivous frame
	    ctx = canvas.getContext('2d'),
	    gradient = ctx.createLinearGradient(0, 0, 0, 300);
	    gradient.addColorStop(1, '#0f0');
	    gradient.addColorStop(0.5, '#ff0');
	    gradient.addColorStop(0, '#f00');
	    var drawMeter = function() {
	        var array = new Uint8Array(analyser.frequencyBinCount);
	        analyser.getByteFrequencyData(array);
	        var step = Math.round(array.length / meterNum); //sample limited data from the total array
	        ctx.clearRect(0, 0, cwidth, cheight);
	        for (var i = 0; i < meterNum; i++) {
	            var value = array[i * step];
	            ctx.fillStyle = gradient; //set the filllStyle to gradient for a better look
	            ctx.fillRect(i * 12 /*meterWidth+gap*/ , cheight - value + capHeight /*2 is the gap between meter and cap*/ , meterWidth, cheight); //the meter
	        }
	        requestAnimationFrame(drawMeter);
	    }
	    requestAnimationFrame(drawMeter);
	},
	start:function() {
		if(this.subscriberId==null) this.subscriberId='**';
		this.subscriberId = window.PageBus.subscribe('**', this, this.onMessage, null);
	},
	stop:function() {
		if(this.subscriberId!=null){
			window.PageBus.unsubscribe(this.subscriberId);
			this.subscriberId=null;
		}
	}
}